﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using PhotoshopFile;

namespace ZyGame.Editor.UIBind
{
    class PSBImport : Singleton<PSBImport>
    {
        private PsdFile document;

        public LayerData selection;
        public LayerData[] layers { get; private set; }

        public void Load(string path)
        {
            document = new PsdFile(path, Encoding.Default);
            List<LayerData> datas = new List<LayerData>();
            for (int i = 0; i < document.Layers.Count; i++)
            {
                CreateLayerDataList(document.Layers[i], datas);
            }

            LayerData parent = null;
            List<LayerData> temp = new List<LayerData>();
            foreach (var l in Enumerable.Reverse(datas))
            {
                if (l.isEndGroup)
                {
                    parent = parent != null ? parent.parent : null;
                    continue;
                }

                l.parent = parent;
                if (parent != null)
                    parent.child.Add(l);
                else
                    temp.Add(l);

                if (l.isGroup)
                    parent = l;
            }

            temp.Reverse();
            layers = temp.ToArray();
        }

        private void CreateLayerDataList(Layer layer, List<LayerData> datas)
        {
            datas.Add(
                new LayerData()
                {
                    name = layer.Name,
                    isEndGroup = layer.IsEndGroupMarker,
                    isGroup = layer.IsGroup,
                    font = null,
                    text = layer.Text,
                    texture = layer.texture,
                    position = layer.Rect,
                }
            );

            for (int i = 0; i < layer.Chiled.Count; i++)
            {
                CreateLayerDataList(layer.Chiled[i], datas);
            }
        }
    }
}